package com.wiim.ui;

import java.io.InputStream;

import com.wiim.common.ConstantValue;
import com.wiim.connector.RestClient;
import com.wiim.handler.SHOPCmdHandler;
import com.wiim.interfaceapp.IServiceCommandResult;
import com.wiim.model.ShopData;
import com.wiim.nhapnhap.AppGlobal;
import com.wiim.nhapnhap.CustomFragmentActivity;
import com.wiim.nhapnhap.EgoodApp;
import com.wiim.nhapnhap.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class StoreDetailFragment extends Fragment implements IServiceCommandResult, OnClickListener {
//	private Button btnXemanh;
	private TextView tvTen;
	private TextView tvDiach;
//	private TextView tvKhuyemai;
//	private Button btnGiam;
	View view;

	@Override
	public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.store_detail_layout, container, false);
		initFeld(view);

		// initData();
		setData();

		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		final InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		mgr.hideSoftInputFromWindow(view.getWindowToken(), 0);
		// rlTop.setVisibility(View.VISIBLE);
		scrollContent.setVisibility(View.VISIBLE);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// rlTop.setVisibility(View.GONE);
	}

	private void setData() {
		Object refundSHOPID = (Object) activity.getPassedValue("SHOPID");
		try {
			String refundSHOPNAME = (String) activity.getPassedValue("SHOPNAME");
			for (int i = 0; i < HomeFrament.ExList.size(); i++) {
				if (refundSHOPNAME.equalsIgnoreCase(HomeFrament.ExList.get(i).ShopName)) {
					refundSHOPID = HomeFrament.ExList.get(i).ShopID;
					activity.setPassValue("SHOPNAME", null);
				}
			}
		} catch (Exception e) {
			Log.v("HAI", "SHOPNAME null");
		}

		if (refundSHOPID != null) {
			ScanningByQrcode = false;
			getData("NONE", (String) refundSHOPID);
		}

	}

	private void initFeld(View view) {
		activity = (CustomFragmentActivity) getActivity();

		fragcontext = StoreDetailFragment.this;
		// rlTop = (RelativeLayout) getActivity().findViewById(R.id.rlTop);
//		btnProfile = (Button) getActivity().findViewById(R.id.btnProfile);
//		btnGilf = (Button) getActivity().findViewById(R.id.btnGilf);
		scrollContent = (ScrollView) view.findViewById(R.id.scrollContent);
		scrollContent1 = (ScrollView) view.findViewById(R.id.scrollContent1);
		scrollContent2 = (ScrollView) view.findViewById(R.id.scrollContent2);
		btnChitiet = (Button) view.findViewById(R.id.btnChitiet);
		btnTichluy = (Button) view.findViewById(R.id.btnDieukien);
		bntDoithuong = (Button) view.findViewById(R.id.btnThongtin);
		btnTichDiem = (Button) view.findViewById(R.id.btnTichDiem);
//		btnXemanh = (Button) view.findViewById(R.id.btnXemanh);
		tvTen = (TextView) view.findViewById(R.id.tvTen);
		tvDiach = (TextView) view.findViewById(R.id.tvDiachi);
//		tvKhuyemai = (TextView) view.findViewById(R.id.tvKhuyemai);
		// Content controls
//		imgRepresent = (ImageView) view.findViewById(R.id.imgStore);
//		tvShopName = (TextView) view.findViewById(R.id.tvShopName);

		tvChitietcuahang = (TextView) view.findViewById(R.id.tvChitietcuahang);
		tvDoithuong = (TextView) view.findViewById(R.id.tvDoithuong);
		tvTichluy = (TextView) view.findViewById(R.id.tvTichluy);
//		btnGiam= (Button) view.findViewById(R.id.btnGiam);

		tvSummoney = (TextView) view.findViewById(R.id.tvSumelabe);
		tvSummoney.setText(new LoginActivity().getUserModel().getRewardPoints());
		btnChitiet.setBackgroundResource(R.drawable.btn_chitiet_choice);
//		btnGiam.setPaintFlags(btnGiam.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

		btnChitiet.setOnClickListener(this);
		btnTichluy.setOnClickListener(this);
		bntDoithuong.setOnClickListener(this);
//		btnProfile.setOnClickListener(this);
//		btnGilf.setOnClickListener(this);
		btnTichDiem.setOnClickListener(this);
//		btnXemanh.setOnClickListener(this);

	}

	private void getData(String qrcode, String shopid) {
		tvChitietcuahang.setText("");
		tvDoithuong.setText("");
		tvTichluy.setText("");

		Bundle cmdData = new Bundle();
		cmdData.putString("qrcode", qrcode);
		cmdData.putString("shopid", shopid);
		AppGlobal.getInstance(StoreDetailFragment.this).startServiceCmd(SHOPCmdHandler.COMMAND_GET_SHOP_BY_QRCODE, new SHOPCmdHandler(), cmdData, true);
	}

	public static ShopData shopdata;

	@Override
	public void processCommandResult(int commandCode, Object resultData) {
		// TODO Auto-generated method stub
		Bundle bResultData = (Bundle) resultData;

		switch (commandCode) {
		case SHOPCmdHandler.COMMAND_GET_SHOP_BY_QRCODE: {
			shopdata = (ShopData) bResultData.getSerializable(EgoodApp.REST_OBJECT_RETURN);
			if (!shopdata.getShopID().equals("")) {

//				tvShopName.setText(shopdata.ShopName);
				tvChitietcuahang.setText(shopdata.Descriptions == null ? "" : shopdata.Descriptions);
				tvDoithuong.setText(shopdata.Descriptions == null ? "" : shopdata.ExchangeAwardModel.Details);
				tvTichluy.setText(shopdata.Descriptions == null ? "" : shopdata.RewardModel.Details);

//				if (shopdata.getAvatar() != null) {
//					Bitmap bm = BitmapFactory.decodeByteArray(shopdata.getAvatar(), 0, shopdata.getAvatar().length);
//					imgRepresent.setImageBitmap(bm);
//				} else {
//					imgRepresent.setImageDrawable(getResources().getDrawable(R.drawable.no_image));
//				}

				if (ScanningByQrcode) {
					if (Boolean.valueOf(shopdata.ExchangeAwardModel.ExchangeAwardStatus) == true && Boolean.valueOf(shopdata.RewardModel.RewardStatus) == true)
						showDialog();
					else
						Toast.makeText(StoreDetailFragment.this.getActivity(), getResources().getString(R.string.msg_promition_unavailable), Toast.LENGTH_LONG).show();
				}

			} else {
				Toast.makeText(StoreDetailFragment.this.getActivity(), getResources().getString(R.string.msg_nosuitable_store), Toast.LENGTH_LONG).show();
			}
			try {
				tvTen.setText(shopdata.ShopName);
				tvDiach.setText(shopdata.Address);
				// tvKhuyemai.setText(shopdata.ShopName);
			} catch (Exception e) {
				// TODO: handle exception
			}
			Log.i("COMMAND_GET_SHOP_BY_QRCODE", "Received");
		}
			break;

		case SHOPCmdHandler.COMMAND_DO_POINTSTRANSACTION: {
			String AddRewardPointsResult = (String) bResultData.getString(EgoodApp.REST_OBJECT_RETURN);
			AddRewardPointsResult = AddRewardPointsResult.replace("\"", "");

			String[] results = AddRewardPointsResult.split("\\..");

			String responsecode = results[0];
			String userbalance = results[1];

			if (responsecode.equalsIgnoreCase(ConstantValue.ValidateDoPointTransactionResponse.SUCCESS.toString())) {
				newFragment.dismiss();

				new LoginActivity().getUserModel().RewardAmount = userbalance;

				tvSummoney.setText(new LoginActivity().getUserModel().getRewardPoints());

				Toast.makeText(StoreDetailFragment.this.getActivity(), getResources().getString(R.string.msg_exchangeaward_success), Toast.LENGTH_LONG).show();
			} else {
				if (responsecode.equalsIgnoreCase(ConstantValue.ValidateDoPointTransactionResponse.NOT_AVAILABLE.toString())) {
					Toast.makeText(StoreDetailFragment.this.getActivity(), getResources().getString(R.string.msg_promition_unavailable), Toast.LENGTH_LONG).show();
				} else if (responsecode.equalsIgnoreCase(ConstantValue.ValidateDoPointTransactionResponse.NOT_ENOUGH_MONEY.toString())) {
					Toast.makeText(StoreDetailFragment.this.getActivity(), getResources().getString(R.string.msg_not_enough_money), Toast.LENGTH_LONG).show();
				} else if (responsecode.equalsIgnoreCase(ConstantValue.ValidateDoPointTransactionResponse.INVALID_VERTIFYCODE.toString())) {
					Toast.makeText(StoreDetailFragment.this.getActivity(), getResources().getString(R.string.msg_verifycode_wrong), Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(StoreDetailFragment.this.getActivity(), getResources().getString(R.string.msg_add_rewardpoints_fail), Toast.LENGTH_LONG).show();
				}
			}
			Log.i("COMMAND_ADD_REWARDPOINTS", AddRewardPointsResult);

		}
			break;

		default:
			break;
		}
	}

	public static DialogFragment newFragment = null;

	public static void doRewardPoints(String verifycode) {
		Bundle cmdData = new Bundle();

		cmdData.putString("transactiontype", ConstantValue.PointTransactionType.EXCHANGE_AWARD.toString());

		cmdData.putString("userid", new LoginActivity().getUserModel().UserId);
		cmdData.putString("fullname", new LoginActivity().getUserModel().Fullname);

		cmdData.putString("shopid", shopdata.ShopID);
		cmdData.putString("shopname", shopdata.ShopName);

		cmdData.putString("rewardid", shopdata.RewardModel.RewardID);
		cmdData.putString("exchangeawardid", shopdata.ExchangeAwardModel.ExchangeAwardID);

		cmdData.putString("verifycode", verifycode);

		AppGlobal.getInstance(fragcontext).startServiceCmd(SHOPCmdHandler.COMMAND_DO_POINTSTRANSACTION, new SHOPCmdHandler(), cmdData, true);
	}

	public void showDialog() {
		// if (!ScanningByQrcode)
		// return;
		// DialogFragment.show() will take care of adding the fragment
		// in a transaction. We also want to remove any currently showing
		// dialog, so make our own transaction and take care of that here.
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		Fragment prev = getFragmentManager().findFragmentByTag("dialog");
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);

		// Create and show the dialog.
		newFragment = MyDialogFragment.newInstance(1);
		newFragment.show(ft, "dialog");

		// newFragment.dismiss();
	}

	public static class MyDialogFragment extends DialogFragment {
		int mNum;

		static MyDialogFragment newInstance(int num) {
			MyDialogFragment f = new MyDialogFragment();

			// Supply NUM input as an argument.
			Bundle args = new Bundle();
			args.putInt("num", num);
			f.setArguments(args);

			return f;
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			mNum = getArguments().getInt("num");

			// Pick a style based on the num.
			// int style = DialogFragment.STYLE_NORMAL, theme = 0;
			// switch ((mNum-1)%6) {
			// case 1: style = DialogFragment.STYLE_NO_TITLE; break;
			// case 2: style = DialogFragment.STYLE_NO_FRAME; break;
			// case 3: style = DialogFragment.STYLE_NO_INPUT; break;
			// case 4: style = DialogFragment.STYLE_NORMAL; break;
			// case 5: style = DialogFragment.STYLE_NORMAL; break;
			// case 6: style = DialogFragment.STYLE_NO_TITLE; break;
			// case 7: style = DialogFragment.STYLE_NO_FRAME; break;
			// case 8: style = DialogFragment.STYLE_NORMAL; break;
			// }
			// switch ((mNum-1)%6) {
			// case 4: theme = android.R.style.Theme_Holo; break;
			// case 5: theme = android.R.style.Theme_Holo_Light_Dialog; break;
			// case 6: theme = android.R.style.Theme_Holo_Light; break;
			// case 7: theme = android.R.style.Theme_Holo_Light_Panel; break;
			// case 8: theme = android.R.style.Theme_Holo_Light; break;
			// }
			setStyle(DialogFragment.STYLE_NO_FRAME, android.R.style.Theme_Translucent_NoTitleBar);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View v = inflater.inflate(R.layout.popup_exchange_options, container, false);

			final LinearLayout lnDoithuong = (LinearLayout) v.findViewById(R.id.lnDoithuong);
			final LinearLayout lnInputVerifycode = (LinearLayout) v.findViewById(R.id.lnInputVerifycode);

			final EditText edtVerifycode = (EditText) v.findViewById(R.id.edtVerifycode);
			final Button btnConfirmVerifycode = (Button) v.findViewById(R.id.btnConfirmVerifycode);

			final Button btnDoithuong = (Button) v.findViewById(R.id.btnDoithuong);
			final Button btnTichdiem = (Button) v.findViewById(R.id.btnTichdiem);

			final TextView tvpShopName = (TextView) v.findViewById(R.id.tvpShopName);
			final TextView tvpShopAddress = (TextView) v.findViewById(R.id.tvpShopAddress);

			lnDoithuong.setVisibility(View.GONE);
			lnInputVerifycode.setVisibility(View.VISIBLE);

			tvpShopName.setText(shopdata.ShopName);
			tvpShopAddress.setText(shopdata.Address);

			ImageView imgStore = (ImageView) v.findViewById(R.id.imgStore);

			if (shopdata.getAvatar() != null) {
//				Bitmap bitmap = BitmapFactory.decodeByteArray(shopdata.getAvatar(), 0, shopdata.getAvatar().length);
//				imgStore.setImageBitmap(bitmap);
								
				new DownloadImageTask(imgStore).execute(shopdata.getAvatar());				
			} else {
				imgStore.setImageDrawable(getResources().getDrawable(R.drawable.no_image));
			}

			btnConfirmVerifycode.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (TextUtils.isEmpty(edtVerifycode.getText())) {
						Toast.makeText(getActivity(), getString(R.string.str_Vuilong), Toast.LENGTH_SHORT).show();
					} else {
						doRewardPoints(edtVerifycode.getText().toString().trim());
					}
					
				}
			});

			return v;
		}
		
		private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
			ImageView bmImage;

			public DownloadImageTask(ImageView bmImage) {
			    this.bmImage = bmImage;
			}

			protected Bitmap doInBackground(String... urls) {
			    String urldisplay = urls[0];
			    Bitmap mIcon11 = null;
			    try {
			        InputStream in = new java.net.URL(urldisplay).openStream();
			        mIcon11 = BitmapFactory.decodeStream(in);
			    } catch (Exception e) {
			        Log.e("Error", e.getMessage());
			        e.printStackTrace();
			    }
			    return mIcon11;
			}

			protected void onPostExecute(Bitmap result) {		   
				bmImage.setImageBitmap(result);
			}
		}
	}

	public static final int REQUEST_CODE_QR = 0x0000c0de;

	public void TurnWebcameOn() {
		Intent intent = new Intent("com.google.zxing.client.android.SCANQR");
		intent.setPackage("com.wiim.nhapnhap");
		intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
		startActivityForResult(intent, REQUEST_CODE_QR);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == REQUEST_CODE_QR) {
			if (resultCode == Activity.RESULT_OK) {
				String tagCode = intent.getStringExtra("SCAN_RESULT").trim();
				Log.i("QRcode: ", tagCode);
				ScanningByQrcode = true;
				if ( tagCode.matches(".*[0-9].*") && tagCode.matches(".*[A-Z].*") ) {
					getData(tagCode, "NONE");
				}else{
					Toast.makeText(StoreDetailFragment.this.getActivity(), getResources().getString(R.string.msg_qrtag_invalid), Toast.LENGTH_LONG).show();
				}
				// showDialog();
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (v == btnChitiet) {
			scrollContent.setVisibility(View.VISIBLE);
			scrollContent1.setVisibility(View.GONE);
			scrollContent2.setVisibility(View.GONE);
			btnChitiet.setBackgroundResource(R.drawable.btn_chitiet_choice);
			bntDoithuong.setBackgroundResource(R.drawable.btn_thongtin);
			btnTichluy.setBackgroundResource(R.drawable.btn_dieukien);
		}

		if (v == bntDoithuong) {
			scrollContent.setVisibility(View.GONE);
			scrollContent1.setVisibility(View.GONE);
			scrollContent2.setVisibility(View.VISIBLE);
			btnChitiet.setBackgroundResource(R.drawable.btn_chitiet);
			bntDoithuong.setBackgroundResource(R.drawable.btn_thongtin_choice);
			btnTichluy.setBackgroundResource(R.drawable.btn_dieukien);
		}

		if (v == btnTichluy) {
			scrollContent.setVisibility(View.GONE);
			scrollContent1.setVisibility(View.VISIBLE);
			scrollContent2.setVisibility(View.GONE);
			btnChitiet.setBackgroundResource(R.drawable.btn_chitiet);
			bntDoithuong.setBackgroundResource(R.drawable.btn_thongtin);
			btnTichluy.setBackgroundResource(R.drawable.btn_dieukien_choice);
		}

//		if (v == btnProfile) {
//			// rlTop.setVisibility(View.GONE);
//			((CustomFragmentActivity) getActivity()).replaceFragment(ConstantValue.THONGTIN_TK_FRAGMENT, false);
//		}
//
//		if (v == btnGilf) {
//			// rlTop.setVisibility(View.GONE);
//			((CustomFragmentActivity) getActivity()).replaceFragment(ConstantValue.DOITHUONG_FRAGMENT, false);
//		}

		if (v == btnTichDiem) {
			TurnWebcameOn();
		}
//		if (v == btnXemanh) {
//			// rlTop.setVisibility(View.GONE);
//			((CustomFragmentActivity) getActivity()).replaceFragment(ConstantValue.XEMANH_FRAGMENT, false);
//		}
	}

//	private TextView tvShopName;
	private CustomFragmentActivity activity;
	private boolean ScanningByQrcode = true;
	public static Fragment fragcontext;
	public static boolean isRewardTab = true;
	// private RelativeLayout rlTop;
	private ScrollView scrollContent;
	private ScrollView scrollContent1;
	private ScrollView scrollContent2;
	private Button btnChitiet;
	private Button btnTichluy;
	private Button bntDoithuong;
	private Button btnProfile;
	private Button btnGilf, btnTichDiem;
	private TextView tvChitietcuahang, tvDoithuong, tvTichluy;
	private TextView tvSummoney;
//	private ImageView imgRepresent;
	

}
